package brandroid.BarAndDrink;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class BarMap extends MapActivity{
	
	private LocationManager locationManager;
	private MapController mapController;
	private LocationListener locationListener;
	private MapView mapView;
	private Drawable drawable;
	private BarItemOverlay itemizedOverlay;
	private List<Overlay> mapOverlays;
	private SQLiteAdapter mySQLiteAdapter;
	private Cursor cursor;
	private Geocoder newPoint;
	//private GpsStatus status;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_screen);
		mapView = (MapView) findViewById(R.id.mapview);
		
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationListener = new NetworkLocationListener();
		
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 30, locationListener);
		//locationManager.getGpsStatus(status);
		mapController = mapView.getController();
		mapController.setZoom(16);
		
		mapOverlays = mapView.getOverlays();
		drawable = this.getResources().getDrawable(R.drawable.emo_im_lips_are_sealed);
		itemizedOverlay = new BarItemOverlay(drawable, this);
		
		GeoPoint initGeoPoint = new GeoPoint((int)(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1E6),
				(int)(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1E6));
		CenterLocation(initGeoPoint);
		//getGeoPointFomAddress("");
//		try {
//			getCoordinates();
//		} catch (FileNotFoundException e) {
//			Toast.makeText(this, "Exception error during directory",
//					Toast.LENGTH_SHORT).show();
//			e.printStackTrace();
//		}
	}
	
	public List<Address> getGeoPointFomAddress(ArrayList<String> address) {
		//address = "200 main st fountain city 54629"; //Used for testing the function
		
		List<Address> addressList = new ArrayList<Address>();
		Geocoder newPoint = new Geocoder(this, Locale.getDefault());
		try {
			int size = address.size();
			for (int count = 0; count <= size; count++) {
			addressList = newPoint.getFromLocationName(address.get(count), 1);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return addressList;
	}
	
	private void CenterLocation(GeoPoint centerGeoPoint)
	 {
	  mapController.animateTo(centerGeoPoint);
	  OverlayItem overlayitem = new OverlayItem(centerGeoPoint, "You are here!", "Work in progress.");
	  
	  itemizedOverlay.addOverlay(overlayitem);
	  mapOverlays.add(itemizedOverlay);
	 };

	private class NetworkLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				GeoPoint point = new GeoPoint(
						(int) (location.getLatitude() * 1E6),
						(int) (location.getLongitude() * 1E6));

				mapController.animateTo(point);
				mapController.setZoom(16);
				mapView.invalidate();
				
				String address = ConvertPointToLocation(point);
			    Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
			}

		}
	
		

		
		
		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			
		}
	}
	
	@Override
	protected void onResume() {
	    super.onResume();
	    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, locationListener);
	}

	@Override
	protected void onPause() {
	    super.onPause();
	    locationManager.removeUpdates(locationListener);
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private List<Address> getCoordinates() throws FileNotFoundException {
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File (sdCard.getAbsolutePath() + "/barstalker/temp" );
		dir.mkdirs();
		File file = new File(dir, "List");
		mySQLiteAdapter = new SQLiteAdapter(this);
		//FileOutputStream fOS = new FileOutputStream(file);
		//OutputStreamWriter myWriter = new OutputStreamWriter(fOS);
		
		ArrayList<String> data = new ArrayList<String>();
		mySQLiteAdapter.openToRead();
		cursor = mySQLiteAdapter.queueAll();
		startManagingCursor(cursor);
		cursor.moveToFirst();
		do {
			data.add(cursor.getString(1) + " " + cursor.getString(3) + " " + cursor.getString(4) + " "
					+ cursor.getString(5));
		} while (cursor.moveToNext());

		List<Address> addressList = new ArrayList<Address>();
		newPoint = new Geocoder(this, Locale.getDefault());
		try {
			int size = data.size();
			for (int count = 0; count < size; count++) {
				addressList.addAll(newPoint.getFromLocationName(
						data.get(count), 1));
				//myWriter.append(addressList.toString());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return addressList;
	}
	
	public String ConvertPointToLocation(GeoPoint point) {   
	    String address = "";
	    Geocoder geoCoder = new Geocoder(
	        getBaseContext(), Locale.getDefault());
	    try {
	      List<Address> addresses = geoCoder.getFromLocation(
	        point.getLatitudeE6()  / 1E6, 
	        point.getLongitudeE6() / 1E6, 1);
	 
	      if (addresses.size() > 0) {
	        for (int index = 0; 
		index < addresses.get(0).getMaxAddressLineIndex(); index++)
	          address += addresses.get(0).getAddressLine(index) + " ";
	      }
	    }
	    catch (IOException e) {        
	      e.printStackTrace();
	    }   
	    
	    return address;
	  } 
	
}
